package io.github.dunwu.javacore.io;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

/**
 * 管道流
 *
 * @author Zhang Peng
 * @date 2018/4/26
 */
public class PipedStreamDemo {

	public static void main(String[] args) {
		Send s = new Send();
		Receive r = new Receive();
		try {
			s.getPos().connect(r.getPis()); // 连接管道
		} catch (IOException e) {
			e.printStackTrace();
		}
		new Thread(s).start(); // 启动线程
		new Thread(r).start(); // 启动线程
	}

	static class Send implements Runnable {

		private PipedOutputStream pos = null;

		Send() {
			pos = new PipedOutputStream(); // 实例化输出流
		}

		@Override
		public void run() {
			String str = "Hello World!!!";
			try {
				pos.write(str.getBytes());
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				pos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		/**
		 * 得到此线程的管道输出流
		 */
		PipedOutputStream getPos() {
			return pos;
		}

	}

	static class Receive implements Runnable {

		private PipedInputStream pis = null;

		Receive() {
			pis = new PipedInputStream();
		}

		@Override
		public void run() {
			byte[] b = new byte[1024];
			int len = 0;
			try {
				len = pis.read(b);
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				pis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			System.out.println("接收的内容为：" + new String(b, 0, len));
		}

		/**
		 * 得到此线程的管道输入流
		 */
		PipedInputStream getPis() {
			return pis;
		}

	}

}
